import { getAction, downloadFile, getFileAccessHttpUrl } from '@/api/manage'
import { getFlowFormDictData } from '@/api/dict'
import { queryDepartTreeList } from '@/api/api'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
export const ProcessTableMixins = {
  data() {
    return {
      defColumns: [], // 表格默认全部列
      columns: [], // 页面表格列
      settingColumns: [], // 自定义表格列设置
      seriaColumns: [
        { type: 'checkbox', width: 50 },
        { type: 'seq', width: 60 }
      ],
      statusColumns: {
        title: '进展',
        width: 100,
        align: 'center',
        field: 'status',
        slots: { default: 'status' }
      },
      source: {
        title: '来源',
        align: 'center',
        width: 100,
        field: 'businessId',
        slots: { default: ({ row }) => {
          let dom = ''
          const text = filterDictTextByCache('bpm_source_type', row.category)
          switch (row.category) {
            case '0':// 台账进度管理跳转
              dom = (<a onClick={() =>
                this.$router.push({ path: '/saleLedger/YsLedgerScoreList', query: { id: row.businessId }})
              }>{text}</a>)
              break
            default:
              ''
          }
          return [dom]
        } }
      },
      actionColumns: {
        title: '操作',
        field: 'action',
        align: 'center',
        width: 200,
        fixed: 'right',
        // scopedSlots: { customRender: 'action' }
        slots: { default: 'action' }
      },
      modelData: {}, // 流程数据
      newFormData: {},
      formData: {}, // 流程表单设计器json
      fieldList: [], // 高级查询列表
      id: '', // 流程id
      desformDesignList: [], // 表单设计器组件list（排除布局组件）
      dynamicDataCode: {}, //
      dynamicDataCodeParam: [], // 需要查询的字典或表
      setDynamicDataAjax: {}, // 查询的字典或表数据
      userKeys: [], // 表单设计器用户组件key值
      usernames: [], // 表单需要展示的用户名
      userList: [], // 表单需要展示的用户列表
      deptList: [], // 表单需要展示的部门列表
      isHasDeptCol: false
    }
  },
  computed: {
    getColumns() {
      if (!this.settingColumns || this.settingColumns.length <= 0) {
        return this.defColumns
      } else {
        const cols = this.defColumns.filter(item => {
          if (item.key === 'rowIndex' || item.dataIndex === 'action') { // 序号操作一直展示
            return true
          }
          if (this.settingColumns.includes(item.dataIndex)) { // 只展示配置显示列
            return true
          }
          return false
        })
        return cols
      }
    }
  },
  watch: {
    isHasDeptCol(val) { // 根据是否有部门组件 请求部门数据
      if (val) {
        this.loadDepart()
      }
    }
  },
  async created() {
    await this.init()
    this.loadData()
  },
  methods: {
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      // 加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.currentPage = 1
      }
      var params = this.getQueryParams()// 查询条件
      console.log(params)
      params.createBy = this.userInfo().username// 添加用户查询的条件
      params.modelId = this.id
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          res.result.records.forEach((item) => {
            item.formData = JSON.parse(item.formData)
            this.setUserName(item.formData)
          })
          this.getUserList()
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    init() {
      const id = this.$route.path.replace(this.rootUrLReplace, '')
      if (!id) {
        this.$message.warning('未找到需要查询的流程ID')
        return false
      }
      this.id = this.modelId
      return this.getFormJson(this.id).then((res) => { // 查询已有表单设计器
        if (res.success) {
          this.modelData = res.result
          this.newFormData = res.result ? JSON.parse(res.result.htmlJson) : {}// 保存最新的表单设计数据
          this.desformDesignList = this.getFormList(this.newFormData.list)// 把表单设计数据转换为数组
          this.getDynamicDataCode(this.desformDesignList)
          this.setSuperQueryFieldList()
          this.getDefColumns()
          this.loadDictData()
        } else {
          this.$message.warning(res.message)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    getDefColumns() { // 获取table默认列头//
      const columns = []
      if (this.desformDesignList.length <= 0) {
        return []
      }
      // 判断表格列是否超宽，超宽设置统一宽度80
      const tableWidth = this.$refs.vxeTable.$el.clientWidth
      const width = tableWidth > this.desformDesignList.length * 80 + 510 ? null : 80
      this.desformDesignList.forEach(item => {
        if (item.options.hidden) { // 排除已隐藏
          return false
        }
        const key = item.model ? item.model : item.key
        const column = {
          title: item.label,
          align: 'center',
          field: 'formData.' + key,
          columnsData: item,
          showOverflow: true,
          width: width
        }
        if (['switch', 'uploadImg', 'uploadFile', 'user', 'dept'].indexOf(item.type) >= 0) { // 这几个类型的组件使用scopedSlots渲染
          column.field = key // 方便取值
          column.slots = { default: item.type }
        }
        if (item.type === 'dept' && !this.isHasDeptCol) {
          this.isHasDeptCol = true
        }
        if (item.type === 'user') {
          this.userKeys.push(item.model)
        }
        if (['select', 'radio'].indexOf(item.type) >= 0) { // 下拉框、单选框等渲染方法
          column.slots = { default: ({ row }) => {
            const dynamic = column.columnsData.options.dynamic
            const t = row.formData[key]
            if (dynamic === 'static') {
              return this.getSelectText(item.options.options, t)
            } else if (dynamic === 'distal') {
              const dynamicKey = column.columnsData.options.distal.tableName
              return this.setDynamicDataAjax[dynamicKey] ? this.getSelectText(this.setDynamicDataAjax[dynamicKey], t) : ''
            } else if (dynamic === 'dict') {
              const dynamicKey = column.columnsData.options.dynamicKey
              return this.setDynamicDataAjax[dynamicKey] ? this.getSelectText(this.setDynamicDataAjax[dynamicKey], t) : ''
            }
          } }
        }
        if (['checkbox'].indexOf(item.type) >= 0) { // 复选框等渲染方法
          column.slots = { default: ({ row }) => {
            const t = row.formData[key]
            return t && t.length > 0 ? this.getCheckboxText(item.options.options, t) : ''
          } }
        }
        columns.push(column)
      })
      // if (this.expandColums) { // 拓展列
      //   // this.defColumns = this.defColumns.concat(this.expandColums)
      //   // this.defColumns = [].concat(this.seriaColumns, columns, [this.statusColumns], this.expandColums ? this.expandColums : [], [this.source, this.actionColumns]
      // }else{

      // }
      this.defColumns = [].concat(this.seriaColumns, columns, [this.statusColumns], this.expandColums ? this.expandColums : [], [this.source, this.actionColumns])
    },
    getFormList(data) { // 根据表单设计器json获取组件（不包含布局容器）
      let formList = []
      data.forEach(item => {
        if (item.model && item.type !== 'batch') {
          formList.push(item)
        } else if (item.type === 'card') {
          formList = formList.concat(this.getFormList(item.list))
        } else if (item.type === 'grid') {
          item.columns.forEach(element => {
            formList = formList.concat(this.getFormList(element.list))
          })
        } else if (item.type === 'table') {
          item.trs.forEach(tr => {
            tr.tds.forEach(td => {
              formList = formList.concat(this.getFormList(td.list))
            })
          })
        }
      })
      return formList
    },
    getFormJson(id) { // 获取表单设计器json
      return getAction(this.url.getNewKfdJson, { modelId: id })
    },
    setSuperQueryFieldList() { // 设置高级查询组件数据
      const superQueryFieldList = []
      this.desformDesignList.forEach(item => {
        const obj = {
          type: 'string',
          value: item.model,
          text: item.label
        }
        if (item.type === 'number' || item.type === 'date') {
          obj.type = item.type
        } else if (item.type === 'time') {
          obj.type = 'datetime'
        } else if (item.type === 'user') {
          obj.type = 'select-user'
        } else if (item.type === 'dept') {
          obj.type = 'select-depart'
        } else if (item.type === 'select') {
          obj.type = 'select'
          obj.options = item.options.options
        }
        superQueryFieldList.push(obj)
      })
      this.fieldList = superQueryFieldList
    },
    getSelectText(option, val) {
      let text
      option.forEach(item => {
        if (item.value === val) {
          text = item.label || item.text
          return false
        }
      })
      return text
    },
    getCheckboxText(option, val) {
      const text = []
      option.forEach(item => {
        if (val.indexOf(item.value) >= 0) {
          text.push(item.label)
        }
      })
      return text.join()
    },
    getDynamicDataCode(list) { // 获取表单设计器需要查询的字典
      const that = this
      list.forEach(function(item, i) {
        const dynamic = item.options.dynamic
        const dynamicKey = item.options.dynamicKey
        if (item.options && (dynamic === 'distal' || dynamic === 'dict') && !that.dynamicDataCode[dynamicKey]) {
          if (dynamic === 'distal') {
            that.dynamicDataCodeParam.push({
              type: 'table',
              value: item.options.distal.value,
              label: item.options.distal.label,
              code: item.options.distal.tableName
            })
          } else {
            that.dynamicDataCodeParam.push({
              type: 'dict',
              code: item.options.dynamicKey
            })
          }
          that.dynamicDataCode[dynamic] = true
        }
        if (item.list) {
          that.getDynamicDataCode(item.list)
        } else if (item.columns) {
          item.columns.forEach(column => {
            column.list && that.getDynamicDataCode(column.list)
          })
        }
      })
    },
    refresh() {
      this.init()
      this.loadData()
    },
    downloadRowFile(fileList) {
      this.loading = true
      let count = 0
      for (const file of fileList) {
        const url = getFileAccessHttpUrl(file.url)
        count++
        downloadFile(url, file.name).finally(() => {
          if (--count === 0) {
            this.loading = false
          }
        })
      }
    },
    setUserName(data) { // 获取列表中的用户username
      this.userKeys.forEach(key => {
        this.usernames.indexOf(data[key]) < 0 && this.usernames.push(data[key])
      })
    },
    getUserList() { // 根据用户username 请求用户列表
      getAction('/sys/user/list', { 'username': this.usernames.join(',') }).then((res) => {
        if (res.success) {
          this.userList = res.result.records
        }
      })
    },
    getRealname(usernames) { // 根据username获取真实姓名
      let names = ''
      if (usernames) {
        const currUserNames = usernames.split(',')
        this.userList.forEach(item => {
          if (currUserNames.indexOf(item.username) >= 0) {
            names += ',' + item.realname
          }
        })
        if (names) {
          names = names.substring(1)
        }
      }
      return names
    },
    loadDepart() { // 获取部门列表
      queryDepartTreeList().then(res => {
        if (res.success) {
          this.reWriterWithSlot(res.result)
        }
      })
    },
    reWriterWithSlot(arr) { // 部门树结构 改为数组结构
      for (const item of arr) {
        if (item.children && item.children.length > 0) {
          this.reWriterWithSlot(item.children)
          const temp = Object.assign({}, item)
          temp.children = {}
          this.deptList.push(temp)
        } else {
          this.deptList.push(item)
        }
      }
    },
    initDepartComponent(departId) { // 根据部门code获取部门名称
      let names = ''
      if (departId) {
        const currDepartId = departId.split(',')
        for (const item of this.deptList) {
          if (currDepartId.indexOf(item.orgCode) >= 0) {
            names += ',' + item.title
          }
        }
        if (names) {
          names = names.substring(1)
        }
      }
      return names
    },
    loadDictData() { // 获取字典code
      getFlowFormDictData({ jsonStr: JSON.stringify(this.dynamicDataCodeParam) }).then(res => {
        this.setDynamicDataAjax = res.result
      })
    }
  }
}
